﻿using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.ServiceModel.Web;

namespace ListItTaxi.Web
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class TaxiService
    {
        ListItEntities _taxiEntities = new ListItEntities();
        AjaxPhoneService _ajaxSvc = new AjaxPhoneService();

        [OperationContract]
        public string DoWork()
        {
            // Add your operation implementation here
            _ajaxSvc.ConnectToAPNS();

            return "hello world";
        }

        [OperationContract]
        public List<Taxi> GetAvailableTaxi()
        {
            // Add your operation implementation here
            var result = from taxi in _taxiEntities.Taxis
                         select taxi;

            return result.ToList();
        }

        [OperationContract]
        public void CreateNewJob(string licenseNo, string customerName, string pickupAddress, string destinationAddress, string mobileNo, string telNo)
        {
            var result = from customer in _taxiEntities.Customers
                         where customer.PhoneNumber == mobileNo
                         select customer;

            var customerList = result.ToList<Customer>();
            ActiveJob job = null;

            if (customerList.Count > 0)
            {
                foreach (var customer in customerList)
                {
                    job = ActiveJob.CreateActiveJob(licenseNo, pickupAddress, destinationAddress, DateTime.Now, customer.DeviceID, mobileNo, telNo, customerName, false);
                    break;
                }
            }
            else
                job = ActiveJob.CreateActiveJob(licenseNo, pickupAddress, destinationAddress, DateTime.Now, "ABC123", mobileNo, telNo, customerName, false); 

            _taxiEntities.AddToActiveJobs(job);
            _taxiEntities.SaveChanges();
            _ajaxSvc.PushJob(job);
           }

        #region IService Members

        [OperationContract]
        [WebGet(UriTemplate = "test/random", ResponseFormat = WebMessageFormat.Json)]
        string GetTestData()
        {
            return "hello";
        }
        #endregion
    }
}
